package spring.cloud.tasks.executor.listener.task_execute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.common.Service;
import spring.cloud.tasks.executor.listener.election.LeaderElectionService;
import spring.cloud.tasks.executor.task.TaskExecutor;
import spring.cloud.tasks.executor.utils.HostUtil;

@Slf4j
@Setter
@Getter
public class TaskExecutorInfoService extends Service {

    private LeaderElectionService leaderElectionService;

    public TaskExecutorInfoService(final TaskExecutor taskExecutor) {
        super(taskExecutor);
    }

    @Override
    public void start() {
        leaderElectionService = taskExecutor.getLeaderElectionService();
    }

    /**
     * 清除立即运行的标记
     */
    public void clearRunOneTimePath() {
        this.getTaskNodeStorage().removeTaskNodeIfExisted(ExecutorNode.getRunOneTimePath(executorId));
    }

    /**
     * 清除立即终止作业的标记
     */
    public void clearStopOneTimePath() {
        this.getTaskNodeStorage().removeTaskNodeIfExisted(ExecutorNode.getStopOneTimePath(executorId));
    }

    public void resetCount() {
        persistProcessSuccessCount(0);
        persistProcessFailureCount(0);

    }

    /**
     * 持久化统计处理数据成功的数量的数据.
     *
     * @param processSuccessCount 成功数
     */
    public void persistProcessSuccessCount(final int processSuccessCount) {
        this.getTaskNodeStorage().replaceTaskNode(ExecutorNode.getProcessSuccessCountNode(executorId), processSuccessCount);
    }

    /**
     * 持久化统计处理数据失败的数量的数据.
     *
     * @param processFailureCount 失败数
     */
    public void persistProcessFailureCount(final int processFailureCount) {
        this.getTaskNodeStorage().replaceTaskNode(ExecutorNode.getProcessFailureCountNode(executorId), processFailureCount);
    }


    /**
     * 持久化作业服务器上线相关信息.
     */
    public void persistExecutorOnline() {
        if (!leaderElectionService.hasLeader()) {
            leaderElectionService.leaderElection();
        }
        persistIp();
        ephemeralPersistStatusNodeReady();
    }

    private void persistIp() {
        this.getTaskNodeStorage().fillTaskNodeIfNullOrOverwrite(ExecutorNode.getIpNode(executorId), HostUtil.cachedIpAddress);
    }

    private void ephemeralPersistStatusNodeReady() {
        this.getTaskNodeStorage().fillEphemeralTaskNode(ExecutorNode.getStatusNode(executorId), "");
    }


}
